package cn.hy.controller;

import cn.hy.constants.LoginConstants;
import cn.hy.redis.key.UserKey;
import cn.hy.response.R;
import cn.hy.service.UserService;
import cn.hy.vo.UserVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/users")
public class LoginController {
    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/login")
    public R<Void> login(@RequestBody @Validated UserVo userVo, HttpServletResponse response) {
        String token = userService.login(userVo);
        addCookie(response, token);
        return R.success();
    }

    @PostMapping("/logout")
    public R<Void> logout() {
        stringRedisTemplate.delete(LoginConstants.TOKEN);
        return R.success();
    }

    @PostMapping("/signUp")
    public R<Void> signUp(@RequestBody @Validated UserVo userVo) {
        userService.signUp(userVo);
        return R.success();
    }

    private void addCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(LoginConstants.TOKEN, token);
        cookie.setMaxAge(UserKey.TOKEN.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
